#include <iostream>
#include <memory>
#include <cctype>
#include <vector>
#include "udp_server.hpp"

using namespace ns_server;
using std:: cout;
using std:: endl;
using std:: string;


static void  usage(string proc)
{
    cout << "usage：\t\n\t" << proc.c_str() << " port" << endl;
}

string transformUpp(string str)
{
    string res;
    for(auto &ch : str)
    {
        if(isalpha(ch))
            res += toupper(ch);
        else
            res += ch;
    }
    return res;
}


static bool isPass(string cmd)
{
    std::vector<string> cmp = {"rm","killed","while"};
    bool pass = true;
    for(auto& str : cmp)
    {
        auto sub = cmd.find(str);
        if(sub != string::npos) //表示没找到
            pass = false;
    }
    return pass;
}
string excuteCom(string cmd)
{
    //执行命令检测是否能够通过
    if(!isPass(cmd))
    {
        return "You are bad man!";
    }
    FILE* fp = popen(cmd.c_str(),"r");
    string res;
    char line[1024];
    while(fgets(line,sizeof(line),fp) != nullptr)
    {
        res += line;
    }
    return res;
}

int main(int argc,char* argv[])
{
    // cout << "udp_server..." << endl;
    //未来呢我想让这样调用udp服务器， ./udp_server 8888 
    //调用的时候传给我端口号
    // unique_ptr<UdpServer> usvr(new UdpServer(8880/*,"1.1.1.1"*/));
    if(argc != 2)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    // std::unique_ptr<UdpServer> usvr(new UdpServer(port));

    // std::unique_ptr<UdpServer> usvr(new UdpServer(transformUpp,port));
    std::unique_ptr<UdpServer> usvr(new UdpServer(excuteCom,port));



    usvr->InitServer();
    usvr->Start();
    return 0;
}